function BCAremoveInfo () {
    // Removes the building information completely to avoid loading large images.
    
    var tbls = document.getElementsByTagName ("table");
    for (var i=tbls.length-1; i>=0; i--) {
        var style = tbls[i].getAttribute ("style");
        if (style && (style.indexOf("bgd.gif") != -1)) {
            if (tbls[i].parentNode.nodeName.toUpperCase() != "FORM") {
                tbls[i].parentNode.removeChild (tbls[i]);
                return;
            }
        }
    }
}
// //////////////////////////////////////////////////////////
// Foes panel
// //////////////////////////////////////////////////////////

function BCAcheckPilot (name, id, alliance, faction) {
    var my = localStorage.getItem ('po_ffm_my_settings');
    var fa = localStorage.getItem ('po_ffm_faction_settings');
    var factionOverrides = localStorage.getItem ('po_ffm_faction_overrides')=="false"?false:true;
    
    var myLvl = 0;
    var faLvl = 0;
    if (my && my.length>0) myLvl = BCAcheckPilotFF (name, id, alliance, faction, my);
    if (fa && fa.length>0) faLvl = BCAcheckPilotFF (name, id, alliance, faction, fa);
    
    if (factionOverrides) {
        if (faLvl == 0) return myLvl;
        if (faLvl > 0 && myLvl > 0) return Math.max(faLvl, myLvl);
        if (faLvl < 0 && myLvl < 0) return Math.min(faLvl, myLvl);
        return faLvl;
    }
    if (myLvl == 0) return faLvl;
    if (faLvl > 0 && myLvl > 0) return Math.max(faLvl, myLvl);
    if (faLvl < 0 && myLvl < 0) return Math.min(faLvl, myLvl);
    return myLvl;
}

function BCAcheckPilotFF (name, id, alliance, faction, ff) {
    var ffs = ff.split("]");
    var friend = ffs[0];
    var foe = ffs[1];
    
    // Check ID if provided. If not, check name
    if (id) {
        if (friend.indexOf ("#"+id+";") != -1) return 3;
        if (foe.indexOf ("#"+id+";") != -1) return -3;
    } else if (name) {
        if (friend.indexOf (name+"#") != -1) return 3;
        if (foe.indexOf (name+"#") != -1) return -3;
    }
    
    // Check Alliance
    if (alliance) {
        if (friend.indexOf (alliance+";") != -1) return 2;
        if (foe.indexOf (alliance+";") != -1) return -2;
    }
    
    // Check Faction
    if (faction) {
        if (friend.indexOf (faction+";") != -1) return 1;
        if (foe.indexOf (faction+";") != -1) return -1;
    }
    return 0;
}

function BCAinstallFoesPanel () {
    // Find the Other Ships table
    var ths = document.getElementsByTagName ("th");
    var os = null;
    for (i=0; i<ths.length; i++) {
        if (ths[i].textContent == "Other Ships") {
            os = ths[i].parentNode.parentNode;
        }
    }
    if (!os) return;
    var topTr = os.parentNode.parentNode.parentNode;
    var td = document.createElement ("td");
    td.setAttribute ("style", "vertical-align: top;border-left:2px solid red;");
    topTr.appendChild (td);
    td.innerHTML = "<table style='vertical-alignment:top;'><tbody>\
                        <tr><th>Foes</th></tr>\
                        <tr><td><table><tbody id=bca_foes_panel></tbody></table></td></tr>\
                    </tbody></table>"
    var panel = document.getElementById ("bca_foes_panel");
    
    // Loop over pilot links and process them
    var sort = new Array ();
    var lnks = os.getElementsByTagName ("a");
    for (var i=0; i<lnks.length; i++) {
        var link = lnks[i];
        var href = link.getAttribute ("href");
        if (href.indexOf ("building.php?detail_type=player") == -1) continue;
        
        // OK, now we have a link to the pilot so let's work with it.
        var name = link.textContent;
        var id = href.split("=")[2];
        var ally =  "- No alliance participation";
        var allyLnk = link.parentNode.getElementsByTagName ("font")[1];
        if (allyLnk) ally = allyLnk.textContent;
        var fact = BCAgetFaction (link.parentNode.previousSibling);
        
        var ff = BCAcheckPilot (name, id, ally, fact);
        
        if (ff > 0) continue; // We're not interested in friends. Only Enemies and neutrals
        var div = document.createElement ("tbody");
        div.innerHTML = "<tr po_ffm_ff='"+ff+"' po_ffm_id='"+id+"' id='bca_foe_"+id+"' refreshed='false'><td>\
                            <a style='color: red;' href='ship2ship_combat.php?playerid="+id+"'>"+name+"</a>\
                            &nbsp(<a id='bca_other_pilot_info_"+id+"' href='javascript:BCAgetOtherShipInfo(\""+id+"\");void(0);'>e-refresh status</a>)\
                        </td></tr>";
        sort.push (div.firstChild);
        panel.appendChild (div.firstChild);
        
        //POlog ("BCA: Name:"+name+" ID:"+id+" Ally:"+ally+" Faction:"+fact+" FF:"+ff);
    }
    BCAsortPilots (sort);
    panel.innerHTML="";
    for (var i=0; i<sort.length; i++){
        panel.appendChild (sort[i]);
    }
}

function BCAgetOtherShipInfo (pilotID) {
    POgetOtherShipInfo (pilotID, BCAshowOtherPilotInfo);
}

function BCArefreshNextPilot () {
    var panel = document.getElementById ("bca_foes_panel");
    if (!panel) return;

    for (var i=0; i<panel.childNodes.length; i++) {
        var pilot = panel.childNodes[i];
        if (pilot.getAttribute ("refreshed")== "false") {
            BCAgetOtherShipInfo (pilot.getAttribute ("po_ffm_id"));
            return;
        }
    }
}

var sortSettings;
function BCAsortPilots (otherShips) {
    var my = localStorage.getItem ('po_ffm_my_settings');
    var fa = localStorage.getItem ('po_ffm_faction_settings');
    var factionOverrides = localStorage.getItem ('po_ffm_faction_overrides')=="false"?false:true;
    sortSettings = factionOverrides==true?fa+";"+my:my+";"+fa;
    
    otherShips.sort (BCAcomparePilots);
}

function BCAcomparePilots (first, second) {
    // More negative number = more up the sip should be in the list
    var ff1 = Number(first.getAttribute("po_ffm_ff"));
    var ff2 = Number(second.getAttribute("po_ffm_ff"));
    if (ff1 != ff2) {
        if (ff1 == 0) return 1;
        if (ff2 == 0) return -1;
        if (ff1>0 && ff2>0)
            if (ff1 > ff2) return -1;
            else return 1;
        if (ff1 < ff2) return -1;
        else return 1;
    }
    var indFirst = sortSettings.indexOf ("#"+first.getAttribute("po_ffm_id")+";");
    var indSec = sortSettings.indexOf ("#"+second.getAttribute("po_ffm_id")+";");
    
    if (indFirst==-1 && indSec==-1) {
        // None of the pilots is listed directly. Let's check their alliances and factions
        //var ff1 = Number(first.getAttribute ("po_ffm_ally");
        return 0;
    }
    if (indFirst==-1) return -1;
    if (indSec==-1) return 1;
    if (indFirst < indSec) return -1;
    return 1;
}

function BCAgetFaction (cell) {
    var factions = cell.getElementsByTagName ("img");
    for (var i=0; i<factions.length; i++) {
        var faction = factions[i];
        var file = faction.getAttribute("src").split ("/");
        file = file[file.length-1];
        if (file.indexOf("fed")!=-1) return "Federation";
        if (file.indexOf("uni")!=-1) return "Union";
        if (file.indexOf("emp")!=-1) return "Empire";
    }
    return "- No faction alignment";
}

function BCAshowOtherPilotInfo (status, pilotID, ship, hull, armor, shield) {
    if (!status) return;
    var pilot = document.getElementById ("bca_other_pilot_info_"+pilotID);
    if (!pilot) return;
    pilot.textContent = ship+" H:"+hull+" A:"+armor+" S:"+shield;
    pilot.parentNode.parentNode.setAttribute ("refreshed", "true");
}

// //////////////////////////////////////////////////////////
// End: Foes panel
// //////////////////////////////////////////////////////////

// //////////////////////////////////////////////////////////
// MyArmor panel
// //////////////////////////////////////////////////////////
function BCAinstallMyArmorPanel () {
    // Find the Other Ships table
    var ths = document.getElementsByTagName ("th");
    var ob = null;
    for (i=0; i<ths.length; i++) {
        if (ths[i].textContent == "Owned by") {
            ob = ths[i].parentNode.parentNode.parentNode;
        }
    }
    if (!ob) return;
    var status = ob.cloneNode (false);
    status.setAttribute ("cellspacing", "0");
    var armorPoints = localStorage.getItem ('po_bca_armor_points');
    var drugs = localStorage.getItem("po_bca_default_drugs");
    //status.setAttribute ("cellpadding", "0");
    status.innerHTML = "<tbody><tr><th colspan=3>My ship status <a style='font-size:9px; color:blue' id='bca_refresh_armor_link' refreshing='false' href='javascript:BCArefreshArmor();void(0);'>(q-refresh status)</a></th></tr>\
                       <tr><td>Hull:</td><td id='bca_my_hull'></td></tr>\
                       <tr><td>Armor:</td><td><span id='bca_my_armor'></span> / <span id='bca_max_armor'>"+armorPoints+"</span></td></tr>\
                       <tr><td>Shield:</td><td id='bca_my_shield'></td></tr>\
                       <tr><td style='border-top:1px solid white'>Bots:</td><td id='bca_bots_avail' style='border-top:1px solid white'>??</td><td style='border-top:1px solid white'><a style='font-size:9px; color:DeepSkyBlue' id='bca_take_bots_link' href='void(0);'>use <span id='bca_take_bots_amount'>??</span> bots</a></td></tr>\
                       <tr><td>Drugs:</td><td id='bca_drugs'>??</td><td style='font-size:9px; color:DeepSkyBlue'>use <a style='font-size:9px; color:DeepSkyBlue' href='javascript:BCAtakeDrugs("+drugs+");void(0);'>"+drugs+"</a> | \
                        <a style='font-size:9px; color:DeepSkyBlue' href='javascript:BCAtakeDrugs(1);void(0);'>1</a> | \
                        <a style='font-size:9px; color:DeepSkyBlue' href='javascript:BCAtakeDrugs(2);void(0);'>2</a> | \
                        <a style='font-size:9px; color:DeepSkyBlue' href='javascript:BCAtakeDrugs(5);void(0);'>5</a>\
                       </td></tr>\
                       </tbody>";
    ob.parentNode.insertBefore (status, ob);
    ob.parentNode.insertBefore (document.createElement ("br"), ob);
    
    var div = document.createElement ("div");
    div.innerHTML = "<div id='bca_message_area' style='display:none;'><br><div id='bca_message_text' style='color:red;font-size:20px'></div></div>";
    ob.parentNode.insertBefore (div.firstChild, status.nextSibling);
    
    
    //BCArefreshArmor ();
    //BCAreadMyShipCargo();
    BCAshowBotsDrugs ();
}

function BCAshowMessage (msg, timeout, color) {
    var area = document.getElementById ('bca_message_area');
    var text = document.getElementById ('bca_message_text');
    if (!area || !text) return;
    area.style.display = "block";
    text.style.color = color?color:"red";
    text.textContent = msg;
    //if (timeout) timeout = timeout *1000;
    //else timeout = 2000;
    //setTimeout (BCAhideMessage, timeout);
}

function BCAhideMessage () {
    BCAshowMessage (".", "blue");
}

function BCArefreshArmor () {
    var lnk = document.getElementById ('bca_refresh_armor_link');
    if (!lnk || lnk.getAttribute ("refreshing") == "true") return;
    
    lnk.textContent = "(.......)";
    lnk.setAttribute ("refreshing", "true");
    
    POgetMyShipStats (BCAshowMyArmor);
}

function BCAgetCargoAmount (commodity, subtract) {
    // Commodity can be either Robots or Drugs
    // Find the table with cargo
    // If the Subtract value is set, the method actually sets a new value to the element which equals to CurrentValue - Subtract
    var tds = document.getElementsByTagName ("th");
    var tb = null;
    for (var i=0; i<tds.length; i++) {
        if (tds[i].textContent == "Resource") {
            tb = tds[i].parentNode.parentNode;
            break;
        }
    }
    // If the table does not exist at all, no bots or drugs are on board
    if (!tb) return 0;
    
    // Go through the rows and search for robots. Skip first row = header
    for (var i=1; i<tb.rows.length; i++){
        var tr = tb.rows[i];
        if (tr.cells[0].firstChild.getAttribute("alt") == commodity) {
            var current = Number (tr.cells[1].textContent);
            if (subtract) {
                current -= subtract;
                tr.cells[1].textContent = current;
            }
            return current;
        }
    }
    
    // No row with robots in the cargo table
    return 0;
}

function BCAshowMyArmor (status, hull, hullMax, armor, armorMax, armorStrength, shield, shieldMax, cargo, cargoMax, fuel, fuelMax) {
    var lnk = document.getElementById ('bca_refresh_armor_link');
    if (!lnk) return;
    lnk.setAttribute ("refreshing", "false");
    
    if (status == false) {
        lnk.textContent = "(error)";
        return;
    }
    lnk.textContent = "(q-refresh status)";
    
    var arm = document.getElementById ('bca_my_armor');
    arm.textContent = armor;//armor+" / "+armorMax;
    document.getElementById ('bca_my_hull').textContent = hull+" / "+hullMax;
    document.getElementById ('bca_my_shield').textContent = shield+" / "+shieldMax;
    
    var avail = BCAgetCargoAmount("Robots");
    var bots = POgetBotsToRepair (armorStrength, armor, armorMax);
    
    if (avail == 0) {
        BCAshowMessage ("Out of bots!!!", 2, "red");
    } else if (avail < bots) {
        BCAshowMessage ("Not enough bots to repair fully!!!", 2, "yellow");
    } else if (avail < 10) {
        BCAshowMessage ("Low on bots!!!", 2, "yellow");
    } else {
        BCAhideMessage ();
    }
    
    
    //armor = 300;
    //bots = 1;
    
    // Set the amount of bots to take to the amount of bots available if necessary
    if (avail < bots) bots = avail;
    
    if (armor < (armorMax-5)) {
        document.getElementById ('bca_take_bots_amount').textContent = bots;
        document.getElementById ('bca_take_bots_link').setAttribute ("href", "javascript:BCAtakeBots("+bots+");void(0);");
    } else {
        document.getElementById ('bca_take_bots_amount').textContent = 0;
        document.getElementById ('bca_take_bots_link').setAttribute ("href", "javascript:void(0);");
    }
    
    var health = (armor *100) / armorMax;
    if (health > 95) arm.parentNode.setAttribute ("style", "color:lime");
    else if (health > 50) arm.parentNode.setAttribute ("style", "color:yellow");
    else arm.parentNode.setAttribute ("style", "color:red");
    
    var health = (hull *100) / hullMax;
    if (health > 95) document.getElementById ('bca_my_hull').setAttribute ("style", "color:lime");
    else if (health > 50) document.getElementById ('bca_my_hull').setAttribute ("style", "color:yellow");
    else document.getElementById ('bca_my_hull').setAttribute ("style", "color:red");
    
    var health = (shield *100) / shieldMax;
    if (health > 95) document.getElementById ('bca_my_shield').setAttribute ("style", "color:lime");
    else if (health > 50) document.getElementById ('bca_my_shield').setAttribute ("style", "color:yellow");
    else document.getElementById ('bca_my_shield').setAttribute ("style", "color:red");
}

function BCAshowBotsDrugs () {
    var elem = document.getElementById ('bca_bots_avail');
    var bots = BCAgetCargoAmount("Robots");
    var drugs = BCAgetCargoAmount("Drugs");
    elem.textContent = bots;
    elem.style.color = bots==0?"red":bots>9?"lime":"yellow";
    var take = document.getElementById ('bca_take_bots_amount');
    if (Number(take.textContent) > bots) {
        document.getElementById ('bca_take_bots_amount').textContent = bots;
        document.getElementById ('bca_take_bots_link').setAttribute ("href", "javascript:BCAtakeBots("+bots+");void(0);");
    }
    
    var elem = document.getElementById ('bca_drugs');
    elem.textContent = drugs;
    elem.style.color = drugs==0?"red":drugs>5?"lime":"yellow";
    
    if (bots == 0) {
        BCAshowMessage ("Out of bots!!!", 2, "red");
    } else if (bots < 10) {
        BCAshowMessage ("Low on bots!!!", 2, "yellow");
    } else {
        BCAhideMessage ();
    }
    
}

function BCAtakeBots (amount) {
    if (amount == -1) {
        amount = Number (document.getElementById ('bca_take_bots_amount').textContent);
    }
    if (isNaN (amount)) {
        BCAshowMessage ("Refresh Ship and Cargo first.");
        return;
    } else {
        BCAhideMessage ();
    }
    if (amount == 0) return;
    POuseResource (8, amount, BCArefreshArmor, "building.php", "post");
    BCAgetCargoAmount ("Robots", amount);
    BCAshowBotsDrugs ();
}

function BCAtakeDrugs (amount) {
    if (amount == -1) {
        amount = document.getElementById ('bca_drugs').textContent;
    }
    POuseResource (51, amount, BCArefreshScreen);
    BCAgetCargoAmount ("Drugs", amount, "building.php", "post");
}

// //////////////////////////////////////////////////////////
// End: MyArmor panel
// //////////////////////////////////////////////////////////

// //////////////////////////////////////////////////////////
// Hotkeys
// //////////////////////////////////////////////////////////
window.addEventListener("keypress",BCAkeyboardAction,true);

function BCAkeyboardAction (e) {
    if(window.name == '' || e.ctrlKey) return;
    if (e.target.nodeName.toUpperCase() == 'INPUT') return;
    var keynum = e.which;
    var key = String.fromCharCode(keynum).toLowerCase();

    if (key == "3") BCAfightFirst ();
    else if (key == "1") BCAretreat ();
    else if (key == "2") BCArefreshScreen ();
    else if (key == "4") BCAtakeBots (-1);
    else if (key == "5") BCAtakeDrugs (-1);
    else if (key == "q") BCArefreshArmor ();
    else if (key == "e") BCArefreshNextPilot ();
    else if (key == "a") BCAwinFight (e.altKey);
    else if (key == "d") BCAwinRetreat ();
    else if (key == "f") BCAwinFight (e.altKey, true);

}

function BCAwinRetreat () {
    POajaxPost ("building.php", "POST", "retreat=Retreat");
    BCAretreat()
}

function BCAwinFight (forceFight, damageBuilding) {
    var avail = BCAgetCargoAmount("Robots");
    BCAhideMessage ();
    var take = document.getElementById ('bca_take_bots_amount').textContent;
    if (take == "??") {
        // Ship status not refreshed. Let's refresh it now.
        BCArefreshArmor ();
        return;
    } else {
        take = Number (take);
        if (take > 0) {
            // Repair the ship
            BCAtakeBots (take);
            return;
        } else {
            // No damage or no bots. Lot's check.
            var armor = Number(document.getElementById ('bca_my_armor').textContent);
            var max = Number(document.getElementById ('bca_max_armor').textContent);
            
            if (armor >= (max-5)) {
                // No damage, let's fight
                BCAfightFirst (damageBuilding);
                return;
            } else {
                // There's some damage so we don't have any bots to repair it
                var minArmor = localStorage.getItem ("po_bca_min_armor");
                if (minArmor) minArmor = Number (minArmor);
                else minArmor = 0;
                if (armor >= minArmor) {
                    // We can't repair but armor is still above the pre-set minimum level. Let's fight
                    BCAfightFirst (damageBuilding);
                } else {
                    // We don't have enough armor
                    if (forceFight) {
                        // Fighting with ALT key = user wants to fight despite the low armor and no bots
                        BCAfightFirst (damageBuilding);
                    } else {
                        // No ALT pressed so let's just inform about low armor and no bots
                        BCAshowMessage ("Low armor and no bots to repair !!!  Use ALT+A to attack anyway.", 3, "red");
                    }
                }
                return;
            }
        }
    }
}

function BCAfightFirst (damageBuilding) {
    if (damageBuilding) {
        var btn = document.getElementsByName ("destroy")[0];
        if (!btn) {
            BCArefreshScreen ();
            return;
        }
        btn.click ();
    } else {
        var panel = document.getElementById ("bca_foes_panel");
        if (!panel) {
            BCArefreshScreen();
            return;
        }
        var first = panel.firstChild;
        if (!first || first.tagName.toLowerCase() != "tr") return;
        window.location = "ship2ship_combat.php?playerid="+first.getAttribute ("po_ffm_id");
    }
}

function BCArefreshScreen () {
    window.location = "building.php";
}

function BCAretreat () {
    var inps = document.getElementsByTagName ("input");
    for (var i=0; i<inps.length; i++) {
        if (inps[i].getAttribute ("name") == "retreat") {
            inps[i].click();
            return;
        }
    }
    window.location = "main.php";
}

// //////////////////////////////////////////////////////////
// End: Hotkeys
// //////////////////////////////////////////////////////////

BCAhideMessage ();
BCAremoveInfo ();
BCAinstallFoesPanel();
BCAinstallMyArmorPanel ();
